package com.heima.user.service.impl;

import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.UpdateById;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.client.ArticleFeign;
import com.heima.client.WemediaFeign;
import com.heima.common.dtos.PageResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.model.article.dtos.AuthorDto;
import com.heima.model.media.dtos.WmUserDto;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.dtos.UserAuthDto;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserAuth;
import com.heima.user.mapper.ApUserAuthMapper;
import com.heima.user.service.ApUserAuthService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.user.service.ApUserService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;

/**
 * <p>
 * APP实名认证信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2022-10-18
 */
@Service
@Slf4j
public class ApUserAuthServiceImpl extends ServiceImpl<ApUserAuthMapper, ApUserAuth> implements ApUserAuthService {

    @Autowired
    private ApUserService apUserService;

    @Autowired
    private WemediaFeign wemediaFeign;
    @Autowired
    private ArticleFeign articleFeign;

    @Override
    public PageResult<UserAuthDto> findByPage(AuthDto dto) {

//        设置分页条件
        IPage<ApUserAuth> iPage = new Page<>(dto.getPage(), dto.getSize());
//        设置查询条件 where status = ?
        LambdaQueryWrapper<ApUserAuth> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(dto.getStatus() != null, ApUserAuth::getStatus, dto.getStatus());
//        分页查询
        IPage<ApUserAuth> userAuthIPage = page(iPage, queryWrapper);
        if (CollectionUtils.isEmpty(userAuthIPage.getRecords())) {
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
//        构造返回对象
        return new PageResult<>(dto.getPage(),
                dto.getSize(),
                userAuthIPage.getTotal(),
                BeanHelper.copyWithCollection(userAuthIPage.getRecords(), UserAuthDto.class));


    }

    @Override
//    @Transactional(rollbackFor = Exception.class)
    @GlobalTransactional(rollbackFor = Exception.class)
    public void userAuth(AuthDto dto, int status) {
       Integer id = dto.getId();
//修改用户状态，根据主键生成
        ApUserAuth apUserAuth = new ApUserAuth();
        apUserAuth.setId(dto.getId());
        apUserAuth.setStatus(status);
        apUserAuth.setReason(dto.getMsg());
        boolean b = updateById(apUserAuth);
        if (!b) {
            //修改不成功抛出异常
            log.error("修改失败",dto.getId());
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }

        //判断审核状态是否通过，如果不通过直接返回
        if (status == 2) {
            log.error("审核不通过");
            return;
        }
        Integer userId = getById(id).getUserId();

        ApUser apUser = apUserService.getById(userId);

        //创建接口参数
        WmUserDto wmUserDto = new WmUserDto();
        wmUserDto.setApUserId(userId);
        wmUserDto.setName(apUser.getName());
        wmUserDto.setPassword(apUser.getPassword());
        wmUserDto.setStatus(9);
        wmUserDto.setPhone(apUser.getPhone());
        //远程调用自媒体用户
        try {
            Integer wmUserId = wemediaFeign.wmUserSave(wmUserDto);
            wmUserDto.setId(wmUserId);
        }catch (Exception e){
            log.error("远程调用自媒体失败");
            e.printStackTrace();
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }

        //远程调用创建文章作者
        AuthorDto authorDto = new AuthorDto();
        authorDto.setUserId(userId);
        authorDto.setWmUserId(wmUserDto.getId());
        authorDto.setType(2);
        authorDto.setName(apUser.getName());
//        远程调用，创建文章作者
        try {
            Integer authorId = articleFeign.saveAuthor(authorDto);
        }catch (Exception e){
            log.error("远程调用article 失败！");
            e.printStackTrace();
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
        //        修改ap_user表的flag，改为自媒体人-1
        apUser  = new ApUser();
        apUser.setId(userId);
        apUser.setFlag(1);
        boolean b1 = apUserService.updateById(apUser);
        if(!b1){
            log.error("修改flag失败，userId={}",userId);
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
    }
}
